﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTP.Command;
using CTP.Entitys;
using CTP;
using System.Runtime.InteropServices;

namespace CTPDemo4Net
{
    public class CTPCallbackHandle : ICTPCallbackHandle
    {
        internal event EventHandler<CTPEventArgs> OnCallbackEvent;
        internal event EventHandler<CTPEventArgs> OnUpdateOrderStatus;


        /// <summary>
        /// 当CTP接口产生异常时回调
        /// </summary>
        /// <param name="result"></param>
        /// <param name="requestID"></param>
        public void OnError(ReturnInfo result, int requestID)
        {
            CTPEventArgs args = new CTPEventArgs();
            StringBuilder str = new StringBuilder();
            args.strBuilder = str;
            str.AppendFormat("接收到错误信息：" + result.ErrorMessage);
            this.OnCallbackEvent(this, args);

        }


        /// <summary>
        /// 资金帐号登陆回调
        /// </summary>
        public void OnLogin(ReturnInfo result, LoginInfo loginInfo, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("资金账号登陆回调事件--成功标志：{0}，信息代码：{1}，信息：{2},资金账号:{3},登陆状态：{4}", result.IsSuccess, result.ErrorCode, result.ErrorMessage, loginInfo.TradingAccount, loginInfo.IsLogined);
            this.OnCallbackEvent(this, args);
        }

        public void OnLogout(ReturnInfo result, string tradingAccount, int requestId)
        {
            try
            {

                CTPEventArgs args = new CTPEventArgs();
                args.strBuilder.AppendFormat("资金账号登出回调事件--成功标志：{0}，信息代码：{1}，信息：{2},资金账号:{3}", result.IsSuccess, result.ErrorCode, result.ErrorMessage, tradingAccount);
                this.OnCallbackEvent(this, args);
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 查询帐户概览响应
        /// </summary>
        public void OnAccountSummary(ReturnInfo result, AccountInformation summary, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("查账号信息回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            args.strBuilder.AppendFormat("资金账号：{0},可用资金：{1}，冻结资金：{2}，冻结保证金{3}", summary.UserAccount, summary.Available, summary.FrozenCash, summary.FrozenCommission);
            this.OnCallbackEvent(this, args);
        }

        /// <summary>
        /// 委托单状态回报
        /// </summary>
        public void OnOrderStatus(ReturnInfo result, OrderStatus ord, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.EventName = "OnOrderStatus";
            args.orderstatus = ord;
            args.strBuilder.AppendFormat("委托单状态回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            this.OnCallbackEvent(this, args);
            this.OnUpdateOrderStatus(this, args);
        }

        /// <summary>
        /// 成交回报(分笔)
        /// </summary>
        public void OnOrderFilled(ReturnInfo result, OrderReport ord)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.orderreport = ord;
            args.EventName = "OnOrderFilled";
            args.strBuilder.AppendFormat("成交回报回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            this.OnCallbackEvent(this, args);
            this.OnUpdateOrderStatus(this, args);
        }

        /// <summary>
        /// 查结算信息响应
        /// </summary>
        public void OnQuerySettlementInfo(ReturnInfo result, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("查结算信息回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            this.OnCallbackEvent(this, args);
        }

        /// <summary>
        /// 确认结算信息响应
        /// </summary>
        public void OnConfirmSettlementInfo(ReturnInfo result, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("确认结算信息回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            this.OnCallbackEvent(this, args);
        }

        /// <summary>
        /// 推送持仓
        /// </summary>
        public void OnPosition(ReturnInfo result, PositionInformation[] positions, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("查询持仓信息回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            args.strBuilder.AppendFormat("持仓信息如下：\n");
            for (int i = 0; i < positions.Length; i++)
            {
                args.strBuilder.AppendFormat("资金账号：{0}，证券代码：{1}，持仓方向：{2}，开仓：{3}，平仓：{4}\n", positions[i].UserAccount, positions[i].Symbol, positions[i].PosSide, positions[i].OpenVolume, positions[i].CloseVolume);
            }
            this.OnCallbackEvent(this, args);

        }

        /// <summary>
        /// 推送当日委托
        /// </summary>
        public void OnQueryOrder(ReturnInfo result, Order[] orders, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("查询当日委托回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            args.strBuilder.AppendFormat("当日委托信息如下：\n");
            for (int i = 0; i < orders.Length; i++)
            {
                args.strBuilder.AppendFormat("资金账号：{0}，合约代码：{1}，买卖方向：{2}，多空方向：{3}，委托单号：" + orders[i].OrderID + ",委托数量：{4},已成数量：{5}\n", orders[i].UserAccount, orders[i].Code, orders[i].Side, orders[i].OpenClose, orders[i].Amount, orders[i].FilledAmount);
            }
            this.OnCallbackEvent(this, args);
        }

        /// <summary>
        /// 推送历史委托
        /// </summary>
        public void OnHistoricalOrder(ReturnInfo result, Order[] orders, int requestId)
        {

        }

        /// <summary>
        /// 推送当日成交记录
        /// </summary>
        public void OnQueryFilled(ReturnInfo result, OrderReport[] orders, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.AppendFormat("查询当日成交回调事件--成功标志：{0}，信息代码：{1}，信息：{2}\n", result.IsSuccess, result.ErrorCode, result.ErrorMessage);
            args.strBuilder.AppendFormat("当日成交信息如下：\n");
            for (int i = 0; i < orders.Length; i++)
            {
                args.strBuilder.AppendFormat("资金账号：{0}，买卖方向：{1}，多空方向：{2}\n", orders[i].Account, orders[i].Side, orders[i].OpenClose);
            }
            this.OnCallbackEvent(this, args);
        }

        /// <summary>
        /// 推送历史成交记录
        /// </summary>
        public void OnHistoricalFilled(ReturnInfo result, OrderReport[] orders, int requestId)
        {

        }

        /// <summary>
        /// 查询是否已确认
        /// </summary>
        /// <param name="result"></param>
        /// <param name="confirmInfo"></param>
        /// <param name="requestId"></param>
        public void OnQuerySettlementInfo(ReturnInfo result, SettlementInfoConfirm confirmInfo, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.Append(confirmInfo.IsConfirmed ? "已确认" : "没确认");
            this.OnCallbackEvent(this, args);
        }


        public void OnLoginQoute(ReturnInfo result, LoginInfo loginInfo, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.Append("行情" + (loginInfo.IsLogined ? "已登陆" : "没登陆"));
            this.OnCallbackEvent(this, args);
        }

        public void OnLogoutQoute(ReturnInfo result, string tradingAccount, int requestId)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.Append("行情" + (result.IsSuccess ? "登出成功" : "登出失败"));
            this.OnCallbackEvent(this, args);
        }

        public void OnQoute(QouteInfo qouteInfo)
        {
            CTPEventArgs args = new CTPEventArgs();
            args.strBuilder.Append(qouteInfo.Symbol + ":"+
            " AvgPrice=" + qouteInfo.AvgPrice + 
            " Position=" + qouteInfo.Position
            );
            this.OnCallbackEvent(this, args);
        }
    }
}
